package com.lql.lqlreader.androidlearning.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.lql.lqlreader.MainActivity
import com.lql.lqlreader.R
import com.lql.lqlreader.androidlearning.model.*
import com.lql.lqlreader.androidlearning.sonic.BrowserActivity
import com.lql.lqlreader.androidlearning.sonic.BrowserActivity.*
import com.lql.lqlreader.androidlearning.sonic.MODE_SONIC
import com.lql.lqlreader.androidlearning.sonic.SonicJavaScriptInterface
import com.lql.lqlreader.service.entity.HttpResultEntity
import com.lql.lqlreader.service.subscriber.HttpResultSubscriber
import com.lql.lqlreader.util.HtmlUtils
import com.lql.lqlreader.widget.LoadingDialog
import com.lql.lqlreader.widget.MyLoadMoreView
import com.lql.lqlreader.widget.WishListIconView
import com.youth.banner.Transformer
import com.youth.banner.loader.ImageLoader
import kotlinx.android.synthetic.main.fragment_android_learning_recommend.*
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import timber.log.Timber

class AndroidLearningRecommendFragment : AndroidLearningBaseFragment() {
    private lateinit var recommendAdapter: BaseQuickAdapter<RecommendItem, BaseViewHolder>
    private var firstEnterLoadingDialog: LoadingDialog? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return LayoutInflater.from(context).inflate(R.layout.fragment_android_learning_recommend, container, false)
    }

    override fun pullDownToRefresh() {
        super.pullDownToRefresh()
        fetchBannerListFromServer()
        fetchRecommendListFromServer(pageIndex)
    }

    private fun fetchBannerListFromServer() {
        fetchBannerList().subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : HttpResultSubscriber<List<Banner>>() {
                override fun onSuccess(data: List<Banner>?) {
                    data?.also { renderBanner(it) }
                }

                override fun _onError(status: Int, msg: String?) {  }
            })
    }

    private fun renderBanner(bannerList: List<Banner>) {
        bannerList.map { it.imagePath }.also {
            banner.setImages(it).setBannerAnimation(Transformer.Default).start().setOnBannerListener { position ->
                val banner = bannerList[position]
                startBrowserActivity(context!!, banner.url, banner.title)
                Timber.d("click banner position is %s, the url is %s", position, banner.url)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        banner.startAutoPlay()
    }

    override fun onStop() {
        super.onStop()
        banner.stopAutoPlay()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
        pullDownToRefresh()
    }

    private fun initView() {
        firstEnterLoadingDialog = context?.let { LoadingDialog(it) }
        firstEnterLoadingDialog?.show()

        initBanner()
        initPtrFrame(ptrFrameRecommend, "Android Learning")
        initRecyclerView()
    }

    private fun initRecyclerView() {
        context?.let { initLayoutManager(it) }
        recommendAdapter = object : BaseQuickAdapter<RecommendItem, BaseViewHolder>(R.layout.item_recommend, null) {
            override fun convert(helper: BaseViewHolder?, item: RecommendItem?) {
                item?.takeIf { it.visible == 1 }?.also {
                    val wishListIconView = helper?.getView(R.id.wishListIcon) as WishListIconView
                    wishListIconView.isActivated = it.collect

                    helper.setText(R.id.tv_title, HtmlUtils.translation(it.title))
                        .setText(R.id.tv_author, "作者：${it.author}")
                        .setText(R.id.tv_category, "分类：${it.superChapterName} / ${it.chapterName}")
                        .setText(R.id.tv_niceDate, it.niceDate)
                        .setGone(R.id.tv_refresh, it.fresh)
                        .addOnClickListener(R.id.wishListIcon)
                }
            }
        }

        recommendAdapter.setOnItemClickListener { adapter, view, position ->
            when (view.id) {
                R.id.wishListIcon -> {
                    var loadingDialog: LoadingDialog? = null
                    this.context?.also {
                        loadingDialog = LoadingDialog(it)
                        loadingDialog?.show()
                    }

                    val recommendItem = adapter.getItem(position) as RecommendItem
                    val observable: Observable<HttpResultEntity<String>> = if (view.isActivated) {
                        unCollectInsideArticle(recommendItem.id)
                    } else {
                        collectInsideArticle(recommendItem.id)
                    }
                    observable.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : HttpResultSubscriber<String>() {
                        override fun onSuccess(data: String?) {
                            loadingDialog?.dismiss()
                            recommendItem.collect = !view.isActivated
                            adapter.data[position] = recommendItem
                            adapter.notifyLoadMoreToLoading()
                            (view as WishListIconView).toggleWishlisted()
                        }

                        override fun _onError(status: Int, msg: String?) {
                            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                            loadingDialog?.dismiss()
                        }
                    })
                }
            }
        }

        recommendAdapter.setOnLoadMoreListener({if (pageIndex + 1 == pageCount) {
            recommendAdapter.loadMoreEnd()
        } else {
            fetchRecommendListFromServer(++pageIndex)
        }}, rv_recommend)

        recommendAdapter.setOnItemClickListener { adapter, _, position ->
            val item = adapter.getItem(position) as RecommendItem
            startBrowserActivity(context!!, item.link, item.title)
        }

        recommendAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        recommendAdapter.setLoadMoreView(MyLoadMoreView())

        rv_recommend.layoutManager = layoutManager
        rv_recommend.adapter = recommendAdapter
    }

    private fun fetchRecommendListFromServer(fpageIndex: Int) {
        fetchRecommendList(fpageIndex).subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : HttpResultSubscriber<RecommendList>() {
                override fun onSuccess(data: RecommendList?) {
                    data?.also {
                        renderRecommendList(fpageIndex, it)
                        if (pageIndex == 0 && it.datas.size < it.size) {
                            recommendAdapter.loadMoreEnd()
                        } else if (pageIndex > 0) {
                            recommendAdapter.loadMoreComplete()
                        }
                    }
                }

                override fun onCompleted() {
                    ptrFrameRecommend.refreshComplete()
                    firstEnterLoadingDialog?.dismiss()
                }

                override fun _onError(status: Int, msg: String?) {  }
            })
    }

    private fun renderRecommendList(witchPage: Int, recommendList: RecommendList) {
        if (witchPage == 0) {
            recommendAdapter.setNewData(recommendList.datas)
        } else {
            pageCount = recommendList.pageCount
            recommendAdapter.addData(recommendList.datas)
        }
    }

    private fun initBanner() {
        banner.setDelayTime(3000).setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (context != null && imageView != null) {
                    Glide.with(context).load(path).into(imageView)
                }
            }
        })
    }

    fun startBrowserActivity(context: Context, url: String, title: String) {
        val intent = Intent(context, BrowserActivity::class.java)
        intent.putExtra(PARAM_URL, url)
        intent.putExtra(PARAM_MODE, MODE_SONIC)
        intent.putExtra(PARAM_TITLE, title)
        intent.putExtra(SonicJavaScriptInterface.PARAM_CLICK_TIME, System.currentTimeMillis())
        context.startActivity(intent)
    }

    override fun checkRefresh(): Boolean {
        return recyclerViewFirstItemCanVisible() && (activity as MainActivity).appBarLayoutVerticalOffset >= 0
    }

    fun gotoFirstPage() {
        if (!recyclerViewFirstItemCanVisible()) pullDownToRefresh()
    }

}
